import Axios from "axios";
import { useUserStore } from '@/store'
const userStore = useUserStore()
const baseURL = import.meta.env.VITE_AXIOS_BASE_URL
const CarryToken = import.meta.env.VITE_REQUEST_CARRY_TOKEN
// 实例化Axios
let instance = Axios.create({ baseURL });
// 请求拦截器
instance.interceptors.request.use((req) => {
  // 是否开启携带token请求
  if (CarryToken == 'true') {
    const CarryTokenKey = import.meta.env.VITE_REQUEST_CARRY_TOKEN_POSITION_KEY
    const CarryTokenPRrefix = import.meta.env.VITE_REQUEST_CARRY_TOKEN_POSITION_VALUE_PREFIX || ''
    let token = userStore.token
    req.headers[CarryTokenKey] = `${CarryTokenPRrefix}${token}`
  }
  return req;
});
// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    if (res.data.code == 0) {
      return res.data;
    } else {
      return Promise.reject(res.data);
    }
  },
  (err) => {
    let message = err.message;
    let code = err.code;
    if (message == "Network Error") {
      return Promise.reject({
        code: 500,
        msg: "服务器无法访问",
      });
    } else if (code == "ECONNABORTED") {
      return Promise.reject({
        code: 500,
        msg: "请求超时",
      });
    } else if (message == "Request failed with status code 404") {
      return Promise.reject({
        code: 404,
        msg: "接口不存在",
      });
    } else {
      return Promise.reject({
        code: 5003,
        msg: "接口请求出错,未知错误",
      });
    }
  }
);
export default instance;
